package cn.edu.sdjzu.xg.eagle.dao;

import cn.edu.sdjzu.xg.eagle.entity.Teacher;
import cn.edu.sdjzu.xg.eagle.util.Condition;
import cn.edu.sdjzu.xg.eagle.util.JdbcHelper;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Collection;
import java.util.List;


public class CommonDao {
    private static CommonDao commonDao = new CommonDao();
    private static Collection<Teacher> teachers;
    private CommonDao() {
    }
    public static CommonDao getInstance() {
        return commonDao;
    }
    public int count(Connection connection, String tableName) throws SQLException {
        String sql_count = "SELECT COUNT(id) as cnt FROM " + tableName;
        PreparedStatement pstmt_count = connection.prepareStatement(sql_count);
        int counter = 0;
        ResultSet resultSet_count = pstmt_count.executeQuery();
        if (resultSet_count.next()) {
            counter = resultSet_count.getInt("cnt");
        }
        JdbcHelper.close(resultSet_count, pstmt_count);
        return counter;
    }
    public int count(Connection connection, String tableName, List<Condition> conditionList)throws SQLException{
        StringBuilder sql_count = new StringBuilder("SELECT COUNT(id) as cnt FROM " + tableName);
        if(conditionList !=null){
            String whereClause = Condition.toWhereClause(conditionList);
            sql_count.append(whereClause);
        }
        PreparedStatement pstmt_count = connection.prepareStatement(sql_count.toString());
        int counter = 0;
        ResultSet resultSet_count = pstmt_count.executeQuery();
        if (resultSet_count.next()) {
            counter = resultSet_count.getInt("cnt");
        }
        JdbcHelper.close(resultSet_count, pstmt_count);
        return counter;
    }

}
